import React from 'react';
// also exported from '@storybook/react' if you can deal with breaking changes in 6.1
import { Story, Meta } from '@storybook/react/types-6-0';

import AutoComplete, {
  AutoCompleteProps,
  AutoCompleteDataSourceType,
} from './index';

import Icon from '../Icon';

// 声明故事的所属模块和名称
export default {
  title: 'Components/AutoComplete',
  component: AutoComplete,
} as Meta;

interface LakersPlayerWithNumbers {
  value: string;
  number: number;
}

// 使用的模板
const BaseUseTemplate: Story<AutoCompleteProps> = args => {
  const lakers: Array<LakersPlayerWithNumbers> = [
    {
      value: 'one',
      number: 1,
    },
    {
      value: 'two',
      number: 2,
    },
    {
      value: 'three',
      number: 3,
    },
    {
      value: 'four',
      number: 4,
    },
    {
      value: 'five',
      number: 5,
    },
    {
      value: 'six',
      number: 6,
    },
    {
      value: 'seven',
      number: 7,
    },
    {
      value: 'eight',
      number: 8,
    },
    {
      value: 'nine',
      number: 9,
    },
    {
      value: 'ten',
      number: 10,
    },
    {
      value: 'eleven',
      number: 11,
    },
    {
      value: 'twelve',
      number: 12,
    },
  ];

  const sleep = (m: number) => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, m);
    });
  };

  const genDemoData = async (query: string) => {
    await sleep(3000);
    return lakers.filter(t => t.value.includes(query));
  };

  const handleFetch = async (query: string) => {
    // return lakers.filter(t => t.value.includes(query));
    return await genDemoData(query);
  };

  const renderOption = (
    item: AutoCompleteDataSourceType<LakersPlayerWithNumbers>
  ) => {
    return (
      <p>
        <Icon icon='arrow-left' /> <span>value:{item.value}</span>
        <br />
        <span>number:{item.number}</span>
      </p>
    );
  };

  const onSelect = (
    item: AutoCompleteDataSourceType<LakersPlayerWithNumbers>
  ) => {
    console.log('====================================');
    console.log(item.number);
    console.log('====================================');
  };
  return (
    <AutoComplete
      fetchSuggestions={handleFetch}
      onSelect={onSelect}
      renderOption={renderOption}
    />
  );
};

export const BaseUse = BaseUseTemplate.bind({});
BaseUse.args = {
  onClick: event => console.log(event),
};
BaseUse.storyName = 'AutoComplete 基本使用';
